package com.dantfb.services;

import java.io.File;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.neo4j.shell.util.json.JSONException;

import com.dantfb.DAO.ConnectionDAO;
import com.dantfb.constants.Constants;
import com.dantfb.mailer.EmailManager;
import com.dantfb.util.LogsUtil;

// TODO: Auto-generated Javadoc
/**
 * The Class ConnectionsServlet.
 */
public class ConnectionsServlet extends HttpServlet {

	/** The session. */
	HttpSession session;

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.servlet.GenericServlet#init()
	 */
	public void init() throws ServletException {

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest
	 * , javax.servlet.http.HttpServletResponse)
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		if (Constants.connectionsServiceType.SUBSCRIBE.toString().equals(
				request.getParameter("serviceType"))) {
			String pseudo = request.getParameter("pseudo");
			String password1 = request.getParameter("password1");
			String password2 = request.getParameter("password2");
			String email = request.getParameter("email");

			if (pseudo.trim().equals("") || email.trim().equals("")
					|| password1.trim().equals("")
					|| password2.trim().equals("")) {
				response.sendRedirect("subscribe.jsp?NOTIF=FIELD_EMPTY");
			} else if (!password1.equals(password2)) {
				response.sendRedirect("subscribe.jsp?NOTIF=PASSWORDS_NOT_MATCH");
			} else if (password1.equals(password2) && password1.length() < 6) {
				response.sendRedirect("subscribe.jsp?NOTIF=PASSWORD_NOT_LONG_ENOUGH");
			} else {
				{
					try {
						String uuid = UUID.randomUUID().toString();
						if (ConnectionDAO.getInstance().subscribeService(
								pseudo, password1, email,uuid,true)) {
							  String UPLOAD_DIRECTORY  = (String)request.getServletContext().getRealPath("/")+"images\\profils\\"+uuid;
								 
							boolean success = (new File(UPLOAD_DIRECTORY)).mkdirs();
							response.sendRedirect("index.jsp?NOTIF=SUBSCRIPTION_SUCCEED");
						} else {
							response.sendRedirect("subscribe.jsp?NOTIF=USER_ALREADY_EXIST");
						}
					} catch (NoSuchAlgorithmException | JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						LogsUtil.getInstance().log(
								e,
								this.getClass().getName(),
								Thread.currentThread().getStackTrace()[1]
										.getMethodName());
						response.sendRedirect("subscribe.jsp?NOTIF=TECHNICAL_ERROR");
					}
				}
			}
		} else if (Constants.connectionsServiceType.LOGIN.toString().equals(
				request.getParameter("serviceType"))) {
			String email = request.getParameter("email");
			String password = request.getParameter("password");
			try {
				String UUID = ConnectionDAO.getInstance().isLoginCorrect(email,
						password);
				if (UUID != null) {
					if (!ConnectionDAO.getInstance().isValideAcounte(email)) {
						response.sendRedirect("index.jsp?NOTIF=ACOUNTE_NOT_VALIDATED");
					} else {
						HttpSession session = request.getSession(true);
						session.setAttribute("email", email);
						session.setAttribute("UUID", UUID);
						response.sendRedirect("home.jsp");
					}
				} else {
					response.sendRedirect("index.jsp?NOTIF=LOGIN_ERROR");
				}
			} catch (NoSuchAlgorithmException e) {

				e.printStackTrace();
				LogsUtil.getInstance().log(
						e,
						this.getClass().getName(),
						Thread.currentThread().getStackTrace()[1]
								.getMethodName());
				response.sendRedirect("index.jsp?NOTIF=TECHNICAL_ERROR");
			} catch (JSONException e) {

				e.printStackTrace();
				LogsUtil.getInstance().log(
						e,
						this.getClass().getName(),
						Thread.currentThread().getStackTrace()[1]
								.getMethodName());
				response.sendRedirect("index.jsp?NOTIF=TECHNICAL_ERROR");
			}
		} else if (Constants.connectionsServiceType.FORGOT_PASSWORD_FORM.toString().equals(
				request.getParameter("serviceType"))) {
			
			try {
				if(ConnectionDAO.getInstance().isUserAlreadySubscribed(request.getParameter("email"))){
					String uuid = ConnectionDAO.getInstance().getUUIDByEmail(request.getParameter("email"));
					EmailManager.getInstance().sendForgotPassword(request.getParameter("email"), uuid);
				}
			} catch (JSONException e) {
				e.printStackTrace();
				LogsUtil.getInstance().log(
						e,
						this.getClass().getName(),
						Thread.currentThread().getStackTrace()[1]
								.getMethodName());
				response.sendRedirect("index.jsp?NOTIF=TECHNICAL_ERROR");
			}
			response.sendRedirect("index.jsp?NOTIF=MAIL_FORGOT_PASSWORD_SENT");
			
		} else if (Constants.connectionsServiceType.FORGOT_PASSWORD_DAO.toString().equals(
				request.getParameter("serviceType"))) {
			String password = request.getParameter("password");
			try {
				ConnectionDAO.getInstance().updateNewPassword(request.getParameter("UUID"), password);
			} catch (NoSuchAlgorithmException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				LogsUtil.getInstance().log(
						e,
						this.getClass().getName(),
						Thread.currentThread().getStackTrace()[1]
								.getMethodName());
			}
			response.sendRedirect("index.jsp?NOTIF=NEW_PASSWORD_SET");
		} else if (Constants.connectionsServiceType.EDIT_ACCOUNTE.toString().equals(
				request.getParameter("serviceType"))) {
			String newNickName = request.getParameter("newNickName");
			String uuid =  request.getParameter("uuid");
			try {
				ConnectionDAO.getInstance().updateProfil(uuid, newNickName);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				LogsUtil.getInstance().log(
						e,
						this.getClass().getName(),
						Thread.currentThread().getStackTrace()[1]
								.getMethodName());
			}
			response.sendRedirect("home.jsp?NOTIF=PROFIL_UPDATED");
		} else if (Constants.connectionsServiceType.DELETE_ACCOUNTE.toString().equals(
				request.getParameter("serviceType"))) {
			String password = request.getParameter("password");
			String uuid = (String)request.getSession().getAttribute("UUID");
			String email = ConnectionDAO.getInstance().getEmailByUUID(uuid);
			try {
				if(ConnectionDAO.getInstance().isLoginCorrect(email, password) != null){
				 try {
					ConnectionDAO.getInstance().unsubscibe(uuid);
					request.getSession().removeAttribute("UUID");
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				response.sendRedirect("index.jsp?NOTIF=ACOUNTE_DELETED");
					}
				else{
					response.sendRedirect("home.jsp?NOTIF=ACOUNTE_NOT_DELETED");
				}
			} catch (NoSuchAlgorithmException | JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.servlet.GenericServlet#destroy()
	 */
	public void destroy() {
		// do nothing.
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		if ("disconnect".equals(request.getParameter("action"))) {
			request.getSession().removeAttribute("pseudo");
			request.getSession().removeAttribute("UUID");
			response.sendRedirect("index.jsp");
		}
		if (request.getParameter("token") != null) {
			response.sendRedirect("forgot_password.jsp?token="
					+ request.getParameter("token"));
		}

	}
}
